package com.wannengbang.storemobile.homepage;


import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ethanhua.skeleton.Skeleton;
import com.ethanhua.skeleton.SkeletonScreen;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.wannengbang.storemobile.R;
import com.wannengbang.storemobile.base.BaseActivity;
import com.wannengbang.storemobile.base.DataCallBack;
import com.wannengbang.storemobile.bean.BaseResponseBean;
import com.wannengbang.storemobile.bean.ProductClassifyListBean;
import com.wannengbang.storemobile.bean.ProductListBean;
import com.wannengbang.storemobile.dialog.ChooseClassifyDialog;
import com.wannengbang.storemobile.event.ProductEvent;
import com.wannengbang.storemobile.homepage.adapter.ProductListAdapter;
import com.wannengbang.storemobile.homepage.model.HomePageModelImpl;
import com.wannengbang.storemobile.homepage.model.IHomePageModel;
import com.wannengbang.storemobile.utils.Dp2Px;
import com.wannengbang.storemobile.utils.ToastUtil;
import com.wannengbang.storemobile.widget.AppTitleBar;
import com.wannengbang.storemobile.widget.CommonNoTitleDialog;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ProductListActivity extends BaseActivity implements OnRefreshLoadMoreListener {

    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.ll_add_product)
    LinearLayout llAddProduct;
    @BindView(R.id.ll_in_storage)
    LinearLayout llInStorage;
    @BindView(R.id.ll_no_data)
    LinearLayout llNoData;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private IHomePageModel homePageModel;
    private ProductListAdapter listAdapter;
    private List<ProductListBean.DataBean.ItemListBean> beanList;
    private SkeletonScreen skeletonScreen;
    private String store_goods_category_id = "";
    private CommonNoTitleDialog.Builder dialogBuild;
    private List<ProductClassifyListBean.DataBean.ItemListBean> classifyList = new ArrayList<>();
    private int page = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_list);
        ButterKnife.bind(this);
        registerEventBus();
        initView();
        requestGoodsIndex();
        requestClassifyData();
    }

    public void requestClassifyData() {
        classifyList.add(new ProductClassifyListBean.DataBean.ItemListBean("", "全部"));
        homePageModel.requestProductClassify(new DataCallBack<ProductClassifyListBean>() {
            @Override
            public void onSuccessful(ProductClassifyListBean bean) {
                if (bean.getData().getItemList() != null && bean.getData().getItemList().size() > 0) {
                    classifyList.addAll(bean.getData().getItemList());
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    public void initView() {
        refreshLayout.setRefreshHeader(new ClassicsHeader(mActivity));//设置Header
        refreshLayout.setRefreshFooter(new ClassicsFooter(mActivity));//设置Footer
        refreshLayout.setOnRefreshLoadMoreListener(this);

        homePageModel = new HomePageModelImpl();
        titleBar.setRightClickListener(() -> {
            ChooseClassifyDialog dialog = ChooseClassifyDialog.newInstance(store_goods_category_id, classifyList);
            dialog.show(getSupportFragmentManager(), "dialog");
            dialog.setOnCallBackListener(id -> {
                store_goods_category_id = id;
                refreshData();
            });
        });

        beanList = new ArrayList<>();
        listAdapter = new ProductListAdapter(beanList);
        recyclerView.setLayoutManager(new GridLayoutManager(mActivity, 2));
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int i = parent.getChildLayoutPosition(view) % 2;//每行2个
                switch (i) {
                    case 0://第一个
                        outRect.left = (int) Dp2Px.dp2Px(15);
                        outRect.right = (int) Dp2Px.dp2Px(5);
                        break;
                    case 1://第二个
                        outRect.left = (int) Dp2Px.dp2Px(5);
                        outRect.right = (int) Dp2Px.dp2Px(15);
                        break;
                }
            }
        });
        recyclerView.setAdapter(listAdapter);
        listAdapter.setOnCallBackListener(new ProductListAdapter.onCallBackListener() {
            @Override
            public void onCallBack(int type, int position) {
                // 1删除 2编辑
                if (type == 1) {
                    dialogBuild = new CommonNoTitleDialog.Builder(mActivity);
                    dialogBuild.setMessage("是否删除此商品?");
                    dialogBuild.setPositiveButton("确定", v -> {
                        dialogBuild.dismiss();
                        requestStoreGoodsDelete(beanList.get(position).getId() + "", position);
                    });
                    dialogBuild.setNegativeButton("取消", v -> dialogBuild.dismiss());
                    dialogBuild.setCancelable(false);
                    dialogBuild.show();
                } else if (type == 2) {
                    Intent intent = new Intent(mActivity, ProductEditActivity.class);
                    intent.putExtra("DataBean", beanList.get(position));
                    startActivity(intent);
                }
            }
        });

        skeletonScreen = Skeleton.bind(recyclerView)
                .adapter(listAdapter)
                .color(R.color.shimmer_color_2)
                .shimmer(true)
                .angle(20)
                .frozen(false)
                .duration(1000)
                .count(20)
                .load(R.layout.item_skeleton_product_list)
                .show();
    }

    public void requestStoreGoodsDelete(String id, int position) {
        homePageModel.requestStoreGoodsDelete(id, new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {
                ToastUtil.showShort("删除成功");
                beanList.remove(position);
                listAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    @Subscribe
    public void ReLoginEvent(ProductEvent event) {
        refreshData();
    }

    private void requestGoodsIndex() {
        homePageModel.requestGoodsIndex(page, "1", store_goods_category_id, new DataCallBack<ProductListBean>() {
            @Override
            public void onSuccessful(ProductListBean bean) {
                if (bean.getData().getItemList() != null && bean.getData().getItemList().size() > 0) {
                    beanList.addAll(bean.getData().getItemList());
                    if (page == 1) {
                        refreshLayout.finishRefresh();
                    } else {
                        refreshLayout.finishLoadMore();
                    }
                } else {
                    if (page != 1) {
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    } else {
                        refreshLayout.finishRefresh();
                    }
                }
                if (beanList.size() > 0) {
                    llNoData.setVisibility(View.GONE);
                } else {
                    llNoData.setVisibility(View.VISIBLE);
                }
                listAdapter.notifyDataSetChanged();
                if (page == 1) {
                    skeletonScreen.hide();
                }
            }

            @Override
            public void onFailed(String msg, String code) {
                skeletonScreen.hide();
            }
        });
    }

    @OnClick({R.id.ll_add_product, R.id.ll_in_storage})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_add_product:
                showActivity(BatchAddProductActivity.class);
                break;
            case R.id.ll_in_storage:
                showActivity(BatchInStorageActivity.class);
                break;
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        page++;
        requestGoodsIndex();
        refreshLayout.finishLoadMore(1000);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        refreshData();
    }

    public void refreshData() {
        page = 1;
        beanList.clear();
        requestGoodsIndex();
        refreshLayout.finishRefresh(1000);
    }
}
